using System;
using System.Collections.Generic;
using System.Text;

namespace PlayDeezGames.Common
{
    public class WeightedGenerator<T>
    {
        private Dictionary<T, uint> generationTable = new Dictionary<T, uint>();
        private uint weightTotal=0;
        public void Clear()
        {
            generationTable.Clear();
        }
        public Dictionary<T, uint>.KeyCollection Values
        {
            get
            {
                return generationTable.Keys;
            }
        }
        private void SetWeight(T theValue, uint theWeight)
        {
            if (generationTable.ContainsKey(theValue))
            {
                weightTotal -= generationTable[theValue];
                generationTable[theValue] = theWeight;
            }
            else
            {
                generationTable.Add(theValue, theWeight);
            }
            weightTotal += generationTable[theValue];
        }
        private uint GetWeight(T theValue)
        {
            if (generationTable.ContainsKey(theValue))
            {
                return generationTable[theValue];
            }
            else
            {
                return 0;
            }
        }
        public T Generate(IRandomNumberGenerator theRandomNumberGenerator)
        {
            if (weightTotal > 0)
            {
                uint randomValue = (uint)theRandomNumberGenerator.Next((int)weightTotal);
                foreach (T generatedValue in generationTable.Keys)
                {
                    if (randomValue < generationTable[generatedValue])
                    {
                        return (generatedValue);
                    }
                    else
                    {
                        randomValue -= generationTable[generatedValue];
                    }
                }
            }
            return default(T);
        }
        public uint this[T theValue]
        {
            get
            {
                return GetWeight(theValue);
            }
            set
            {
                SetWeight(theValue, value);
            }
        }
        public WeightedGenerator()
        {
        }
    }

}
